#include "stringtokenizer.h"

#include <string.h>
#include <stdbool.h>

struct StringTokens {
    size_t num_tokens;
    char tokens[128][512];
    char delimiters[128];
};

struct StringTokens * tokens_create( const char * string, const char * delimiters )
{
    struct StringTokens * ret = malloc( sizeof(struct StringTokens) );
    memset( ret, 0, sizeof( struct StringTokens ) );

    ret->num_tokens = 0;
    size_t token_size = 0;

    for ( size_t i = 0; i < strlen( string ); i++ )
    {
        if ( !strchr( delimiters, string[i] ) ) {
            char letter[2] = " ";
            letter[0] = string[i];
            strcat( ret->tokens[ret->num_tokens], letter );
            ++token_size;
        } else if ( token_size != 0 ) {
            ret->delimiters[ret->num_tokens] = string[i];
            ret->num_tokens++;
            token_size = 0;
        }
    }

    if ( token_size != 0 ) {
        ret->delimiters[ret->num_tokens] = '\0';
        ret->num_tokens++;
    }

    return ret;
}

size_t tokens_size( const struct StringTokens * tokens )
{
    return tokens->num_tokens;
}

const char * tokens_get( const struct StringTokens * tokens, size_t i )
{
    return tokens->tokens[i];
}

char tokens_divider_get( const struct StringTokens * tokens, size_t i )
{
    return tokens->delimiters[i];
}

void tokens_free( struct StringTokens * tokens )
{
    free( tokens );
}
